/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "ParticleProcess.h"
#include "../Components/MeshRenderer.h"
#include "../Content/MeshFilter.h"
#include "../Managers/DX11Manager.h"
#include "../DataStructures/Particle.h"
#include "Hogshead.Common.h"
#include "../Content/BlendState.h"
#include "../Content/DepthStencilState.h"
#include "../Content/GeometryShader.h"
#include "../Content/PixelShader.h"
#include "../Content/Pass.h"
#include "../Content/PixelShader.h"
#include "../Content/RasterizerState.h"
#include "../Content/SamplerState.h"

#include <algorithm>


namespace Hogshead
{
	namespace DX11Rendering
	{
		DirectorCPP(Hogshead::DX11Rendering::ParticleProcess)

		ParticleProcess::ParticleProcess(void)
		{
			
		}


		ParticleProcess::~ParticleProcess(void)
		{
		}

		void ParticleProcess::initialize()
		{
			_world_view_projection_buffer = NULL;
			_prev_blend_state = 0;
			_prev_depth_stencil_state = 0;
			_prev_geometry_shader = 0;
			_prev_pixel_shader = 0;
			_prev_rasterizer_state = 0;
			_prev_sampler_state = 0;
			_prev_vertex_shader = 0;

			_light_error = Color(1.0f,0,0);
			_prev_game_time = 0.0f;
			this->_enabled = true;

			
			//create the one cbuffer that is standard and bind it
			DX11Manager::createConstantBuffer( sizeof( WVP), &_world_view_projection_buffer );
		}

		void ParticleProcess::finalize()
		{
			
		}

		void ParticleProcess::update(const GameTimer& in_gt)
		{
			

		}

		void ParticleProcess::registerComponent(IComponent* in_component)
		{
			if(in_component->is<MeshRenderer>())
			{
				this->_registered_components.add(in_component);

				in_component->as<MeshRenderer>()->_registered = true;
				ParticleBufferInfo* pbi = (ParticleBufferInfo*)in_component->as<MeshRenderer>()->_process_specific_data;
				pbi->_first_run = true;
			}
		}

		void ParticleProcess::unregisterComponent(IComponent* in_component)
		{
			_registered_components.swapRemove(in_component);
		}

		void ParticleProcess::setGraphicsState(Pass* in_pass)
		{
			Pass* current_pass = in_pass;
			//set topology
			DX11Manager::setTopology(current_pass->topology());			

			//------------------------
			//set the shaders
				// vertex
			if(!_prev_vertex_shader || current_pass->_vs != _prev_vertex_shader)
			{
				//for now just set the layout (check to be more optimal at a later time
				DX11Manager::setInputLayout( current_pass->_vs->_input_layout );
				//set the VS
				DX11Manager::setVertexShader( current_pass->_vs->_vs );
				//save it off as prev
				_prev_vertex_shader = current_pass->_vs;
			}
				//geometry
			if(!_prev_geometry_shader || current_pass->_gs != _prev_geometry_shader)
			{
				//check to see if there is a Geometry Shader
				if(current_pass->_gs)
				{
					//set the GS
					DX11Manager::setGeomentryShader( current_pass->_gs->_gs );
					//save it off as prev
					_prev_geometry_shader = current_pass->_gs;
				}
				else
				{
					//set the GS
					DX11Manager::setGeomentryShader( NULL );
					//save it off as prev
					_prev_geometry_shader = NULL;
				}
			}
				//pixel
			if(!_prev_pixel_shader || current_pass->_ps != _prev_pixel_shader)
			{
				if(current_pass->_ps)
				{
					//set the PS
					DX11Manager::setPixelShader( current_pass->_ps->_ps );
					//save it off as prev
					_prev_pixel_shader = current_pass->_ps;
				}
				else
				{
					DX11Manager::setPixelShader(NULL);
					_prev_pixel_shader = NULL;
				}
			}

							
			

			//-----------------------
			//set other card states: blend, sampler, rasterizer
			if(current_pass->_rasterizer_state)
			{
				if(!_prev_rasterizer_state || current_pass->_rasterizer_state != _prev_rasterizer_state )
				{
					_prev_rasterizer_state = current_pass->_rasterizer_state;
					DX11Manager::setRasterizerState(_prev_rasterizer_state->_rasterizer_state);
				}
			}

			if(current_pass->_blend_state)
			{
				if(!_prev_blend_state || current_pass->_blend_state != _prev_blend_state)
				{
					_prev_blend_state = current_pass->_blend_state;
					DX11Manager::setBlendState( _prev_blend_state->_blend_state, NULL, 0xffffffff );
				}
			}

			if(current_pass->_depth_stencil_state)
			{
				if(!_prev_depth_stencil_state || current_pass->_depth_stencil_state != _prev_depth_stencil_state)
				{
					_prev_depth_stencil_state = current_pass->_depth_stencil_state;
					DX11Manager::setDepthStencilState(_prev_depth_stencil_state->_depth_stencil_state);
				}
			}

			for( int j = 0; j < current_pass->_sampler_states.size(); j++ )
			{
				DX11Manager::setSamplers(j, 1, &current_pass->_sampler_states[j]->_sampler_state, (ShaderBindFlags) (GEOMETRY_SHADER | PIXEL_SHADER));
				
			}
						
		}

		void ParticleProcess::render(Camera* in_active_camera, HashSet<void*>* in_nonculled_components)
		{
			_prev_vertex_shader = NULL;
			_prev_pixel_shader = NULL;
			_prev_geometry_shader = NULL;

			_prev_rasterizer_state = NULL;
			_prev_blend_state = NULL;
			_prev_sampler_state = NULL;
			_prev_depth_stencil_state = NULL;

			//setup the viewport
			D3D11_VIEWPORT viewport;
			viewport.Width = (FLOAT)DX11Manager::getWidth();
			viewport.Height = (FLOAT)DX11Manager::getHeight();
			viewport.MinDepth = 0.0f;
			viewport.MaxDepth = 1.0f;
			viewport.TopLeftX = 0;
			viewport.TopLeftY = 0;
			DX11Manager::setViewport( &viewport );

			for(int i = 0; i < _registered_components.size(); i++)
			{
				//continue if the camera is not looking at this particle system
				//if(!in_nonculled_components->contains(_registered_components[i]))
					//continue;

				MeshRenderer* cur_renderer = _registered_components[i]->as<MeshRenderer>();

				

				//on our first run, we use the initial buffer containing the initial emitters
				ParticleBufferInfo* pbi = (ParticleBufferInfo*)cur_renderer->_process_specific_data;

				
				if(pbi->_first_run)
				{	
					DX11Manager::setVertexBuffer(pbi->getInitBuffer(), pbi->_particle_size);
				}
				//if it isn't our first run, we use the draw vertex buffer
				else
				{
					DX11Manager::setVertexBuffer(pbi->getDrawBuffer(), pbi->_particle_size);
				}
		

				//set our stream output target to the stream output buffer
				ID3D11Buffer* so_buff = pbi->getStreamOutBuffer();
				DX11Manager::setSOTargets(1, &so_buff);

				const Technique* current_draw_tech = cur_renderer->getTechnique(this->_handle);

				//do the birth pass for the particle shader
				Pass* current_pass = current_draw_tech->passes()[0];

				this->setGraphicsState(current_pass);

				//-----------------------
				//set the constant buffers
				//do register 0 from here, get world from the component, bind it to all three we currently use
				if( in_active_camera )
				{
					_world_view_projection._view = in_active_camera->getView();
					_world_view_projection._projection = in_active_camera->getProjection();
					_world_view_projection._camera_position_ws = Vector4(in_active_camera->getParentGameObject()->getTransform().getWorldPosition(), 1.0f);
				}
				else
				{
					error("you will need a camera");
				}
				_world_view_projection._world = cur_renderer->getParentGameObject()->getTransform().getWorldMatrix();
				_world_view_projection._wvp =  _world_view_projection._projection * (_world_view_projection._view *_world_view_projection._world);

				DX11Manager::bindConstantBuffer( &_world_view_projection_buffer, 0, (ShaderBindFlags) (VERTEX_SHADER | HULL_SHADER | DOMAIN_SHADER | GEOMETRY_SHADER | PIXEL_SHADER) );
				DX11Manager::updateSubresource(  _world_view_projection_buffer, &_world_view_projection, 0 );

				//bind lighting to register 1 if it uses lighting
				/*if( cur_renderer->useLighting() )
				{
					_parent->updateSpecularExponent( cur_renderer->getSpecularExponent() );
					DX11Manager::bindConstantBuffer( &DX11Manager::getLightingConstantBuffer() , 1, (ShaderBindFlags) (VERTEX_SHADER | HULL_SHADER | DOMAIN_SHADER | PIXEL_SHADER));
				}*/

				//get the rest from the component.
				for( int j = 0; j < cur_renderer->constantBufferGroup().size(); j++ )
				{
					DX11Manager::bindConstantBuffer( cur_renderer->constantBufferGroup().get(j).buffer(),
						cur_renderer->constantBufferGroup().get(j).registerNumber(),
						cur_renderer->constantBufferGroup().get(j).shaderBindFlags() );
				}

				//update the shader resources
				//more needs to be set here VIA techniques
				if( pbi->getParticleTexture())
				{
					DX11Manager::setPSShaderResource(DIFFUSE, &(pbi->getParticleTexture()->_shader_resource_view));
				}

				/*if(cur_renderer->meshFilter()->_shader_resources[SPECULAR].size() > 0)
				{
					DX11Manager::setPSShaderResource(SPECULAR, &(cur_renderer->meshFilter()->_shader_resources[SPECULAR].get(0))->_shader_resource_view);
				}

				if(cur_renderer->meshFilter()->_shader_resources[NORMAL].size() > 0)
				{
					DX11Manager::setPSShaderResource(NORMAL, &(cur_renderer->meshFilter()->_shader_resources[NORMAL].get(0))->_shader_resource_view);
				}*/

				/*if(cur_renderer->meshFilter()->_shader_resources[TRANSPARENCY].size() > 0)
				{
					DX11Manager::setPSShaderResource(TRANSPARENCY, &(cur_renderer->meshFilter()->_shader_resources[TRANSPARENCY].get(0))->_shader_resource_view);
				}*/

				DX11Manager::setGSShaderResource(5, &pbi->getRandomTexture()->_shader_resource_view);
				DX11Manager::setPSShaderResource(5, &pbi->getRandomTexture()->_shader_resource_view);

				////finally draw the stream output pass (birth pass)
		
				if(pbi->_first_run)
				{
					DX11Manager::draw(pbi->_num_particles, 0);
					pbi->_first_run = false;
				}
				else
				{
					DX11Manager::drawAuto();
				}
	

				//turn off stream output
				ID3D11Buffer* buffer_array[1] = {0};
				DX11Manager::setSOTargets(1,buffer_array);

				//ping pong the stream output and the draw buffers
				std::swap(pbi->_draw_buffer, pbi->_stream_out_buffer);

				//draw the updated particles that we just streamed out
				//if this object isn't in view of the camera, we don't care about it so continue
				if(!cur_renderer->getNeverCull() && !in_nonculled_components->contains(cur_renderer) && _culling)
					continue;

				Pass* draw_pass = current_draw_tech->passes()[1];
				this->setGraphicsState(draw_pass);

				//draw our particles to the screen
				//DX11Manager::draw(1,0);
				DX11Manager::drawAuto();

				pbi->_already_updated = false;
			}
		}



		float ParticleProcess::calcAttenuation(float in_light_distance, float in_light_attenuation)
		{
			float att = in_light_attenuation * in_light_distance;
			return att * att;
		}

		//int ParticleProcess::setLights(IComponent* in_component)
		//{
			
			/*IRenderInfo* render_info = in_component->getRenderInfo(); 
			StaticMesh* current_mesh = NULL;
			if(render_info->is<DX11StaticMeshInfo>())
			{
				current_mesh = render_info->as<DX11StaticMeshInfo>()->_object_to_render;
			

				DX11Manager::_basic_dynamic_struct._ambient_color = current_mesh->_material->_ambient_light;

				_active_lights.clear();

				for(int i = 0; i < _point_lights.size(); i++)
				{		
					float distance_to_light = Vector3::distance(_point_lights.get(i)->getParentGameObject()->getTransform()->getWorldPosition(), in_component->getParentGameObject()->getTransform()->getWorldPosition());
					distance_to_light -= current_mesh->_material->_light_activate_distance;
					distance_to_light = Math::max(distance_to_light, 0.0f);
					if( this->calcAttenuation(distance_to_light, _point_lights[i]->_attenuation_parameter) < 1.0f)
					{		
						_active_lights.add(Pair<float, PointLight*>(distance_to_light,_point_lights[i]));
					}
				}
			

				for(int i = 0; i < 4; i++)
				{
					DX11Manager::_diffuse_dynamic_struct._light_color[i] = Color::Black();
					DX11Manager::_diffuse_dynamic_struct._light_pos[i] = Vector4(0,0,0,0);
					DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(0,0,0,0);
					DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(0,0,0,0);
				}

				if(_active_lights.size() > 4)
				{
					StringBuilder sb;
					sb << "ERROR IN LIGHTING: More than 4 point lights affect single object" << endl;
					sb << "\tObject Affected: " << endl;
					sb << "\tObject Name: " << in_component->getParentGameObject()->_global_name << endl;
					sb << "\tObject Position: " << in_component->getParentGameObject()->getTransform()->getWorldPosition() << endl;
					sb << endl;

					DX11Manager::_basic_dynamic_struct._ambient_color = _light_error;
					for(int i = 0; i < 4; i++)
					{
						DX11Manager::_diffuse_dynamic_struct._light_color[i] = _light_error;
						Vector4 light_pos = _active_lights[i].second->getPosition();
						DX11Manager::_diffuse_dynamic_struct._light_pos[i] = light_pos;
						DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(_active_lights[i].second->_attenuation_parameter, 0,0,0);
						DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(current_mesh->_material->_max_specular,0,0,0);
					}

	#ifdef _DEBUG
					for(int i = 0; i < _active_lights.size(); i++)
					{
						PointLight* cur_light = _active_lights[i].second;
						sb << "\tLight Name: " << cur_light->componentName() << endl;
						sb << "\tLight Position: " << cur_light->getParentGameObject()->getTransform()->getWorldPosition() << endl;
						sb << "\tLight Color: " << cur_light->_light_color._red << ", " << cur_light->_light_color._blue << ", " << cur_light->_light_color._green << endl;
						sb << endl;
					}
					DX11Manager::_logger->write(sb);
					hout << sb;
	#endif
				}
				else
				{
					for(int i = 0; i < _active_lights.size() && i < 4; i++)
					{
						DX11Manager::_diffuse_dynamic_struct._light_color[i] = (_active_lights[i].second->_light_color);
						Vector4 light_pos = _active_lights[i].second->getPosition();
						DX11Manager::_diffuse_dynamic_struct._light_pos[i] = light_pos;
						DX11Manager::_diffuse_dynamic_struct._light_range_parameter[i] = Vector4(_active_lights[i].second->_attenuation_parameter,0,0,0);
						DX11Manager::_specular_dynamic_struct._specular[i] = Vector4(current_mesh->_material->_max_specular,0,0,0);
					}
				}
			}*/
			//return _active_lights.size();
		//}
	}
}